#!/bin/bash

echo "正在构建学习宝库桌面应用..."

# 检查Flutter环境
if ! command -v flutter &> /dev/null; then
    echo "Flutter未安装或未添加到PATH中，请先安装Flutter并确保可以运行flutter命令。"
    exit 1
fi

# 获取操作系统类型
echo "检测操作系统类型..."

# 默认根据当前系统选择构建目标
if [[ "$OSTYPE" == "darwin"* ]]; then
    DEFAULT_PLATFORM="macos"
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
    DEFAULT_PLATFORM="linux"
else
    DEFAULT_PLATFORM="windows"
fi

# 允许通过参数指定平台
TARGET_PLATFORM=${1:-$DEFAULT_PLATFORM}

if [[ "$TARGET_PLATFORM" != "windows" && "$TARGET_PLATFORM" != "macos" && "$TARGET_PLATFORM" != "linux" ]]; then
    echo "不支持的平台: $TARGET_PLATFORM"
    echo "用法: ./build_desktop.sh [windows|macos|linux]"
    exit 1
fi

echo "将为 $TARGET_PLATFORM 平台构建应用"

# 获取依赖
echo "获取依赖..."
flutter pub get
if [ $? -ne 0 ]; then
    echo "获取依赖失败"
    exit 1
fi

# 构建应用
echo "开始构建 $TARGET_PLATFORM 应用..."
flutter build $TARGET_PLATFORM --release
if [ $? -ne 0 ]; then
    echo "构建失败"
    exit 1
fi

echo "构建完成！"

if [ "$TARGET_PLATFORM" = "windows" ]; then
    echo "应用位置: build/windows/runner/Release/"
elif [ "$TARGET_PLATFORM" = "macos" ]; then
    echo "应用位置: build/macos/Build/Products/Release/"
elif [ "$TARGET_PLATFORM" = "linux" ]; then
    echo "应用位置: build/linux/x64/release/bundle/"
fi

echo "感谢使用学习宝库！"